package com.wanqian.redis.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ScheduledMessage;

import javax.jms.*;

/**
 * @Author: wanqian
 * @Date: 2021/3/13 13:11
 */
public class ActiveMQProducer {

    private static final String URL = "tcp://145.170.39.203:61616";

    private static final String QUEUE_NAME = "queue_test";

    private static final String TOPIC_NAME = "topic_test";

    public static void main(String[] args) throws JMSException {
        //根据url创建连接工厂
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(URL);
//        connectionFactory.setUseAsyncSend(true);
        MessageProducer producer = null;
        Connection connection = null;
        Session session = null;
        //创建连接和会话(设置事务和签收)
        try {
            connection = connectionFactory.createConnection();
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            //开启连接
            //创建队列
            Topic topic = session.createTopic(TOPIC_NAME);
            //创建生产者(指定destination)
            producer = session.createProducer(topic);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            connection.start();
            for (int i = 0; i < 3; i++) {
                TextMessage textMessage = session.createTextMessage("消息测试-------" + i);
                //延迟3秒发送
                textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 3 * 1000);
                //间隔5秒发送
                textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 5 * 1000);
                //重复发送5次
                textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 5);
                producer.send(textMessage, new CompletionListener() {
                    @Override
                    public void onCompletion(Message message) {

                    }

                    @Override
                    public void onException(Message message, Exception exception) {

                    }
                });
            }
            //开启事务后，执行commit才会提交消息
            session.commit();
            //关闭资源
            producer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
            //回滚
            session.rollback();
        }
    }
}
